package com.cet.designapplication.pay.strategy.factory;

import com.cet.designapplication.pay.strategy.PayStrategyInterface;
import com.cet.designapplication.pay.strategy.context.PayContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author NSOC
 */

@Component
public class PayContextFactory extends AbstractPayContextFactory<PayContext>{
    private static final Map<String, PayContext> PAY_CONTEXT_MAP = new ConcurrentHashMap<>();

    @Override
    public PayContext getContext(Integer payType) {
        StrategyEnum strategyEnum = StrategyEnum.getPayStrategy(payType);
        PayContext cachedPayContext = PAY_CONTEXT_MAP.get(strategyEnum.name());
        if (cachedPayContext == null) {
            try {
                PayStrategyInterface payStrategy = (PayStrategyInterface) Class.forName(strategyEnum.getValue()).newInstance();
                PayContext payContext = new PayContext(payStrategy);
                PAY_CONTEXT_MAP.put(strategyEnum.name(), payContext);
            } catch (Exception e) {
                throw new UnsupportedOperationException("Get pay strategy failed!");
            }
        }
        return PAY_CONTEXT_MAP.get(strategyEnum.name());
    }
}
